package com.itheima.interceptor;

import com.itheima.common.AuthThreadLocal;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author HeiMa-sw
 * @Description 登录拦截预处理//TODO 17210
 * @Date 14:41 2022/6/12
 **/
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        // 校验token
        if (StringUtils.isEmpty(token)) {
            System.out.println("token不存在");
            return false;
        }
        // 如果token有效，就放行 return true
        // 校验token有效性
        // 将token中的用户信息解析出来，并返回
        // 如果token失效，就拦截 return false
        Claims claims = JwtUtils.getClaims(token);
        if (claims == null) {
            System.out.println("token失效了");
            return false;
        }

        String empId = (String) claims.get("empId");
        if (empId == null) {
            System.out.println("token失效了");
            return false;
        }

        AuthThreadLocal.setAuth(empId);
        System.out.println("我是拦截器，我获取到的员工id为:" + empId);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        System.out.println("我是后置拦截器");
        AuthThreadLocal.remove();
    }

}
